<template>
  <t-drawer v-if="opened" v-model:visible="visible" header="搜索" size="600px" :footer="false">
    <t-input @input="search" />
    <div class="lg-list gl-mt" style="height: calc(100% - 40px); overflow-y: auto">
      <div
        v-for="x in options"
        :key="x.path"
        class="lg-list-item"
        @click="
          $router.push(x.path);
          visible = false;
        "
      >
        <div style="padding: 9px; width: 54px">
          <lg-icon :value="x.icon" style="font-size: 24px" />
        </div>
        <div>
          <div style="line-height: 1.5; color: var(--app-color-text-primary)">{{ x.title }}</div>
          <t-breadcrumb @click.stop>
            <t-breadcrumb-item v-for="y in x.link" :key="y.path" :to="y.path">
              <template #icon> <lg-icon :value="y.icon" /></template>
              {{ y.title }}
            </t-breadcrumb-item>
          </t-breadcrumb>
        </div>
        <div></div>
      </div>
    </div>
  </t-drawer>
</template>

<script setup lang="ts">
import { nextTick, ref, watch } from 'vue';
import { useAccountStore } from '@/store';
import { LgIcon } from '@/soar';

const opened = ref(false);
const visible = ref(false);
const options = ref([]);
let list = [];

watch(
  () => visible.value,
  (v) => {
    if (!v) {
      nextTick(() => {
        setTimeout(() => {
          opened.value = v;
          list = [];
          options.value = [];
        }, 200);
      });
    }
  },
);

function findMenu(list: any[], link: any[]) {
  let rs = [];
  for (const x of list) {
    const ns = [...link, { path: x.path, title: x.meta?.title }];
    if (x.children?.length) {
      rs = rs.concat(findMenu(x.children, ns));
    } else {
      rs.push({ icon: x.meta?.icon, path: x.path, title: x.meta?.title, link: ns });
    }
  }
  return rs;
}

function search(e) {
  e = e.target.value;
  options.value = list.filter((x) => x.link.findIndex((y) => y.title?.includes(e) || y.path?.includes(e)) !== -1);
}

defineExpose({
  open() {
    const { routes } = useAccountStore();
    list = findMenu(routes, []);
    options.value = list;
    opened.value = true;
    nextTick(() => {
      visible.value = true;
    });
  },
});
</script>
<style lang="less" scoped></style>
